<?php

namespace Xrfg\Api\Consume\Job;

use Xrfg\Api\Consume\Models\ConsumeOrders;
use Xrfg\Api\Consume\Models\ConsumeRecommends;
use Xrfg\Api\Consume\Models\ConsumeAccounts;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ReturnXgJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;


    protected $order;

    public function __construct($order,$XG_USDT)
    {
        $this->order = $order;
        $this->XG_USDT = $XG_USDT;
    }

    public function handle()
    {
        try {
            logger('==购买消费券返XG==');
            $this->leader();
        } catch (\Throwable $throwable) {
            Log::info($throwable);
        }
    }

    /**
     * 1单：100U一代收益：50轩谷币
     * 2-3单：200U二代收益：25轩谷币
     * 4-5单：400U三代收益：12.5轩谷币
     * 6-7单：600U四代收益：6.25轩谷币
     * 8-9单：800U五代收益：3.125轩谷币
     * 10-27单：1000U六代收益：1.5625轩谷币
     */
    protected function leader()
    {
        if (!$this->order) {
            return;
        }
        logger($this->order);

        // 第1代
        $parent_id_1 = $this->order->parent_id;
        logger('第1代用户ID：'.$parent_id_1);
        $this->doReturnU(1, $parent_id_1);
        // 第2代
        $order = $this->getOrder($parent_id_1);
        if (!$order) {
            logger('已到创世节点，返XG结束');
            return;
        }
        $parent_id_2 = $order->parent_id;
        logger('第2代用户ID：'.$parent_id_2);
        $this->doReturnU(2, $parent_id_2);
        // 第3代
        $order = $this->getOrder($parent_id_2);
        if (!$order) {
            logger('已到创世节点，返XG结束');
            return;
        }
        $parent_id_3 = $order->parent_id;
        logger('第3代用户ID：'.$parent_id_3);
        $this->doReturnU(3, $parent_id_3);
        // 第4代
        $order = $this->getOrder($parent_id_3);
        if (!$order) {
            logger('已到创世节点，返XG结束');
            return;
        }
        $parent_id_4 = $order->parent_id;
        logger('第4代用户ID：'.$parent_id_4);
        $this->doReturnU(4, $parent_id_4);
        // 第5代
        $order = $this->getOrder($parent_id_4);
        if (!$order) {
            logger('已到创世节点，返XG结束');
            return;
        }
        $parent_id_5 = $order->parent_id;
        logger('第5代用户ID：'.$parent_id_5);
        $this->doReturnU(5, $parent_id_5);
        // 第6代
        $order = $this->getOrder($parent_id_5);
        if (!$order) {
            logger('已到创世节点，返XG结束');
            return;
        }
        $parent_id_6 = $order->parent_id;
        logger('第6代用户ID：'.$parent_id_6);
        $this->doReturnU(6, $parent_id_6);
    }

    // 查询用户订单
    protected function getOrder($user_id)
    {
        $order = ConsumeOrders::where('id', $this->order->id)->where('user_id', $user_id)->first();
        return $order;
    }

    protected function doReturnU($gen, $user_id)
    {
        $reward = 0;
        if ($gen == 1) { // 一代收益：50
            $reward = 50;
        } else if ($gen == 2) { // 二代收益：25
            if ($this->recomendNum($user_id) >= 2) {
                $reward = 25;
            }
        } else if ($gen == 3) { // 三代收益：12.5
            if ($this->recomendNum($user_id) >= 4) {
                $reward = 12.5;
            }
        } else if ($gen == 4) { // 四代收益：6.25
            if ($this->recomendNum($user_id) >= 6) {
                $reward = 6.25;
            }
        } else if ($gen >= 5) { // 五代收益：3.125
            if ($this->recomendNum($user_id) >= 8) {
                $reward =3.125;
            }
        } else if ($gen >= 6) { // 六代收益：1.5625
            if ($this->recomendNum($user_id) >= 10) {
                $reward =1.5625;
            }
        }
        $reward = $reward / $this->XG_USDT;
        logger('返XG数量：'.$reward);

        // 执行返XG逻辑
        if ($reward > 0) {
            // 已结算，不能重复结算
            $isRecommend = ConsumeRecommends::where('user_id', $user_id)
                ->where('order_id', $this->order->id)
                ->where('type', 2)
                ->first();
            if ($isRecommend) {
                logger('已结算，不能重复结算');
                return;
            }

            $xgConsumeAccount = ConsumeAccounts::firstOrCreate([
                'user_id' => $user_id,
                'coin_id' => 2,
            ])->refresh();
            // 返XG明细
            $recommend = new ConsumeRecommends();
            $recommend->user_id = $user_id;
            $recommend->child_user_id = $this->order->user_id;
            $recommend->order_id = $this->order->id;
            $recommend->total = 0;
            $recommend->rate = 0;
            $recommend->profit = $reward;
            $recommend->type = 2;
            $recommend->time = now();

            DB::transaction(function () use ($recommend, $xgConsumeAccount) {
                $recommend->save();

                // 更新账户
                $xgConsumeAccount = ConsumeAccounts::lockForUpdate()->find($xgConsumeAccount->id);
                $xgConsumeAccount->disabledIncrement($recommend->profit);
                $xgConsumeAccount->type = '层级收益';
                $xgConsumeAccount->action_id = $this->order->id;
                $xgConsumeAccount->save();
            });
        }
    }

    // 计算直推单数
    protected function recomendNum($user_id)
    {
        logger('计算'.$user_id.'直推单数');
        // 购买订单
        $sumNumber = ConsumeOrders::where('parent_id', $user_id)->sum('number');
        logger('直推单数'.$sumNumber[0]);
        return $sumNumber[0];
    }

    // 计算直推人数
    protected function recomendCount($user_id)
    {
        logger('计算'.$user_id.'直推人数');
        // 购买订单
        $u = ConsumeOrders::where('parent_id', $user_id)->select('user_id')->distinct()->pluck('user_id')->toArray();
        logger('直推人数：'.count($u));
        return count($u);
    }
}
